import * as robotModel from '../../models/robot';
import * as messageModel from '../../models/user_message';
import * as feedbackModel from '../../models/feedback';
import * as guideModel from '../../models/guide';
import * as versionAppModel from '../../models/version_app';
import * as versionRobotModel from '../../models/version_robot';
import * as bannerModel from '../../models/banner';
import * as bannerRelationModel from '../../models/banner_relation';
import * as bookAlbumModel from '../../models/book_album';
import * as soundAlbumModel from '../../models/sound_album';
import * as validHelp from '../../helps/valid';
import { ValidException, EmptyException, SystemException } from '../../helps/exception';

export function* getMessageList({ robot_id, page, number }) {
  if (!validHelp.Required(robot_id)) throw ValidException('机器人为空');
  if (!validHelp.Page(page, number)) throw ValidException('分页参数错误');
  let robot = yield robotModel.get(robot_id);
  if (!robot) throw EmptyException('机器人不存在');
  let list = yield messageModel.listByUnread(robot_id, page, number);
  return list;
}

export function* addFeedback({ user_id, content }) {
  if (!content) throw ValidException('反馈信息为空');
  yield feedbackModel.add({ user_id, content, admin_id: 0 });
  return {};
}

export function* getGuide() {
  let list = yield guideModel.all('order', 'desc');
  return list;
}

export function* getAppVersion() {
  let record = yield versionAppModel.getLast();
  return record;
}

export function* getRobotVersion() {
  let record = yield versionRobotModel.getLast();
  return record;
}

export function* getBannerList({ page, number }) {
  if (!validHelp.Page(page, number)) throw ValidException('分页参数错误');
  let where = [];
  where.push(['status', '=', 1]);
  let list = yield bannerModel.search(where, page, number);
  return list;
}

export function* getBanner({ banner_id }) {
  if (!validHelp.Required(banner_id)) throw ValidException('Banner为空');
  let banner = yield bannerModel.get(banner_id);
  if (!banner) throw EmptyException('Banner不存在');
  if (banner.status !== 1) throw EmptyException('Banner不存在');
  if (banner.type === 1) return banner;
  let list = yield bannerRelationModel.all(banner_id, 'order', 'desc');
  if (list.length > 0) {
    let ids = list.map(row => row.module_id);
    let realModel = null;
    switch (banner.type) {
      case 1:
        realModel = bookAlbumModel;
        break;
      case 2:
        realModel = soundAlbumModel;
        break;
      default:
        throw SystemException('banner类型错误');
    }
    let model_list = realModel.getIds(ids);
    let map = {};
    model_list.forEach((row) => {
      map[row.id] = row;
    });
    list = list.map((row) => {
      row.info = map[row.module_id];
      return row;
    });
  }
  banner.list = list;
  return banner;
}
